package dao;

import bean.Book;
import utils.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BookDao {
    DbUtil dbUtil=new DbUtil();
    public int addBook(Connection con, Book book){

        int result = 0;
        String sql="insert into book (book_id,book_name,book_price) values (?,?,?)";
        try {
            con =dbUtil.getCon();
            PreparedStatement ps=con.prepareStatement(sql);
            ps.setInt(1,book.getbId());
            ps.setString(2,book.getbName());
            ps.setString(3,book.getbPrice());
            result=ps.executeUpdate();
            dbUtil.closeCon(con);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultSet listBook(Connection con,Book book) throws Exception{
       StringBuffer sb=new StringBuffer("select * from book");
       if(book.getbName()!=null){
           sb.append(" and book_name like '%"+book.getbName()+"%'");  //看不懂
       }
        PreparedStatement ps=con.prepareStatement(sb.toString().replaceFirst("and","where"));
        ResultSet rs=ps.executeQuery();
        return rs;
    }

    /**
     * 图书删除操作
     * @param con
     * @param book
     * @return
     */
    public int deleteBook(Connection con,Book book) throws Exception{
        String sql="delete from book where book_id=? and book_name=? and book_price =?";
        con=dbUtil.getCon();
        PreparedStatement ps=con.prepareStatement(sql);
        ps.setInt(1,book.getbId());
        ps.setString(2,book.getbName());
        ps.setString(3,book.getbPrice());
        return ps.executeUpdate();
    }

    /**
     * 修改图书信息的方法
     * @param con
     * @param book
     * @return
     */
    public int changeBook(Connection con,Book book) throws  Exception{
        con=dbUtil.getCon();
        PreparedStatement ps=con.prepareStatement("update  book set book_name=? ,book_price=? where book_id=?");
        ps.setString(1,book.getbName());
        ps.setString(2,book.getbPrice());
        ps.setInt(3,book.getbId());
        return ps.executeUpdate();
    }
}
